import ezdxf
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.patches import Arc
 
# 指定要读取的DXF文件路径
dxf_file_path = 'output/output_image.dxf'
 
# 加载DXF文件
doc = ezdxf.readfile(dxf_file_path)
msp = doc.modelspace()  # 获取模型空间
 
# 创建一个图形对象和坐标轴对象
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6))  # 1行2列的子图布局

 
# 准备一个列表用于存储所有的线段
rlines = []
blines = []
# 遍历模型空间中的所有实体
for entity in msp:
    if entity.dxftype() == 'LINE':  # 如果是直线
        # 添加起点和终点到lines列表
      
        if entity.dxf.color==1:
         rlines.append([(entity.dxf.start.x, entity.dxf.start.y), 
                      (entity.dxf.end.x, entity.dxf.end.y)])
        elif entity.dxf.color==5:
         blines.append([(entity.dxf.start.x, entity.dxf.start.y), 
                      (entity.dxf.end.x, entity.dxf.end.y)])
    elif entity.dxftype() == 'SPLINE':  # 如果是样条曲线
        fit_points = entity.control_points
        rlines.append([(fit_points[0][0], fit_points[0][1]), 
                      (fit_points[-1][0], fit_points[-1][1])])
    elif entity.dxftype() == 'ARC':  # 如果是圆弧
        arc = entity
        center = (arc.dxf.center.x, arc.dxf.center.y)
        radius = arc.dxf.radius
        start_angle = arc.dxf.start_angle
        end_angle = arc.dxf.end_angle
        if start_angle > end_angle:
            end_angle += 360  # 确保角度范围正确
        
        # 使用matplotlib的Arc类绘制圆弧
        arc_patch = Arc(center, 2*radius, 2*radius, angle=0, 
                         theta1=start_angle, theta2=end_angle, 
                         color='yellow', linewidth=0.5)
        ax2.add_patch(arc_patch)
    else:
        print('未处理的实体类型:', entity.dxftype())
 
# 使用LineCollection绘制所有的线段
line_segments_red  = LineCollection(rlines, linewidths=0.5, colors='red')

ax1.add_collection(line_segments_red)
line_segments_blue = LineCollection(blines, linewidths=0.5, colors='blue')
ax2.add_collection(line_segments_blue)
 
# 设置坐标范围
lines=rlines + blines
ax1.set_xlim(min([min(l[0][0], l[1][0]) for l in lines])-5, max([max(l[0][0], l[1][0]) for l in lines])+5)
ax1.set_ylim(min([min(l[0][1], l[1][1]) for l in lines])-5, max([max(l[0][1], l[1][1]) for l in lines])+5)
ax2.set_xlim(min([min(l[0][0], l[1][0]) for l in lines])-5, max([max(l[0][0], l[1][0]) for l in lines])+5)
ax2.set_ylim(min([min(l[0][1], l[1][1]) for l in lines])-5, max([max(l[0][1], l[1][1]) for l in lines])+5)
  
plt.gca().set_aspect('equal', adjustable='box')  # 固定比例
plt.show()